package com.kaisademo.zhxy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kaisademo.zhxy.pojo.Admin;
import com.kaisademo.zhxy.pojo.LoginForm;
import com.kaisademo.zhxy.pojo.Student;
import com.kaisademo.zhxy.pojo.Teacher;
import com.kaisademo.zhxy.service.AdminService;
import com.kaisademo.zhxy.service.StudentService;
import com.kaisademo.zhxy.service.TeacherService;
import com.kaisademo.zhxy.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

@Api(tags = "系统控制器")
@RestController
@RequestMapping("/sms/system")
public class SystemController {

    @Autowired
    private AdminService adminService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private TeacherService teacherService;

    @PostMapping("/updatePwd/{oldPwd}/{newPwd}")
    public Result updatePwd(
            @PathVariable(value = "olaPwd") String oldPwd,
            @PathVariable(value = "newPwd") String newPwd,
            @RequestHeader String token
    ){
        boolean expiration = JwtHelper.isExpiration(token);
        if(expiration){
            return Result.fail().message("token已失效");
        }

        Long userId = JwtHelper.getUserId(token);
        Integer userType = JwtHelper.getUserType(token);

        oldPwd= MD5.encrypt(oldPwd);
        newPwd= MD5.encrypt(newPwd);

        switch (userType){
            case 1:
                //判断原密码输入是否正确
                LambdaQueryWrapper<Admin> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper1.eq(Admin::getId,userId.intValue());
                lambdaQueryWrapper1.eq(Admin::getPassword,oldPwd);
                Admin admin = adminService.getOne(lambdaQueryWrapper1);
                if(admin != null){
                    admin.setPassword(newPwd);
                    adminService.saveOrUpdate(admin);
                }else {
                    return Result.fail().message("原密码输入错误");
                }
                break;
            case 2:
                //判断原密码输入是否正确
                LambdaQueryWrapper<Student> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper2.eq(Student::getId,userId.intValue());
                lambdaQueryWrapper2.eq(Student::getPassword,oldPwd);
                Student student = studentService.getOne(lambdaQueryWrapper2);
                if(student != null){
                    student.setPassword(newPwd);
                    studentService.saveOrUpdate(student);
                }else {
                    return Result.fail().message("原密码输入错误");
                }
                break;
            case 3:
                //判断原密码输入是否正确
                LambdaQueryWrapper<Teacher> lambdaQueryWrapper3 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper3.eq(Teacher::getId,userId.intValue());
                lambdaQueryWrapper3.eq(Teacher::getPassword,oldPwd);
                Teacher teacher = teacherService.getOne(lambdaQueryWrapper3);
                if(teacher != null){
                    teacher.setPassword(newPwd);
                    teacherService.saveOrUpdate(teacher);
                }else {
                    return Result.fail().message("原密码输入错误");
                }
                break;
        }
        return Result.ok();
    }

    @ApiOperation("头像上传统一入口")
    @PostMapping("/headerImgUpload")
    public Result headerImgUpload(
            @ApiParam("文件二进制数据") @RequestPart("multipartFile") MultipartFile multipartFile
    ){

        //使用UUID随机生成文件名
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        //生成新的文件名字
        String filename = uuid.concat(multipartFile.getOriginalFilename());
        //生成文件的保存路径(实际生产环境这里会使用真正的文件存储服务器)
        String portraitPath ="c:/code/zhxy/target/classes/public/upload/".concat(filename);
        //保存文件
        try {
            multipartFile.transferTo(new File(portraitPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String headerImg ="upload/"+filename;
        return Result.ok(headerImg);
    }

    /**
     * 根据类型主页面跳转
     * @param token
     * @return
     */
    @GetMapping("/getInfo")
    public Result getInfoByToken(@RequestHeader("token") String token){
        //判断token是否过期
        boolean expiration = JwtHelper.isExpiration(token);
        if(expiration){
            return Result.build(null, ResultCodeEnum.CODE_ERROR);
        }
        //如没过期，解析token
        Long userId = JwtHelper.getUserId(token);
        Integer userType = JwtHelper.getUserType(token);
        //根据类型查询相应的登录人

        //创建map集合储存返回结果
        Map<String,Object> map = new LinkedHashMap<>();
        switch (userType){
            case 1:
                Admin admin = adminService.getAdminById(userId);
                map.put("user",admin);
                map.put("userType",1);
                break;
            case 2:
                Student student = studentService.getAdminById(userId);
                map.put("user",student);
                map.put("userType",2);
                break;
            case 3:
                Teacher teacher = teacherService.getAdminById(userId);
                map.put("user",teacher);
                map.put("userType",3);
                break;
        }
        return Result.ok(map);
    }


    @PostMapping("/login")
    public Result login(@RequestBody LoginForm loginForm,HttpServletRequest request){
        //比对验证码是否正确
        HttpSession session = request.getSession();
        String sessionVerifiCode = (String) session.getAttribute("verifiCode");
        String loginFormVerifiCode = loginForm.getVerifiCode();
        if("".equals(sessionVerifiCode) || null == sessionVerifiCode){
            return Result.fail().message("验证码已失效，请刷新后重试");
        }
        if(!sessionVerifiCode.equalsIgnoreCase(loginFormVerifiCode)){
            return Result.fail().message("验证码输入错误，请重新输入");
        }
        //验证码正确后，删除session中的验证码
        session.removeAttribute("verifiCode");
        //分用户类型进行校验

        // 准备一个Map集合,用户存放响应的信息
        Map<String, Object> map = new LinkedHashMap<>();
        switch (loginForm.getUserType()){
            //管理员登陆
            case 1:
                try {
                    // 调用服务层登录方法,根据用户提交的LoginInfo信息,查询对应的Admin对象,找不到返回Null
                    Admin admin = adminService.login(loginForm);
                    if(admin != null){
                        // 登录成功,将用户id和用户类型转换为token口令,作为信息响应给前端
                       map.put("token", JwtHelper.createToken(admin.getId().longValue(),1));
                    }else {
                        return Result.fail().message("用户名或密码错误");
                    }
                    return Result.ok(map);
                } catch (Exception e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }

            //学生登陆
            case 2:
                try {
                    // 调用服务层登录方法,根据用户提交的LoginInfo信息,查询对应的Admin对象,找不到返回Null
                    Student student = studentService.login(loginForm);
                    if(student != null){
                        // 登录成功,将用户id和用户类型转换为token口令,作为信息响应给前端
                        map.put("token", JwtHelper.createToken(student.getId().longValue(),2));
                    }else {
                        return Result.fail().message("用户名或密码错误");
                    }
                    return Result.ok(map);
                } catch (Exception e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }

            //教师登陆
            case 3:
                try {
                    // 调用服务层登录方法,根据用户提交的LoginInfo信息,查询对应的Admin对象,找不到返回Null
                    Teacher teacher = teacherService.login(loginForm);
                    if(teacher != null){
                        // 登录成功,将用户id和用户类型转换为token口令,作为信息响应给前端
                        map.put("token", JwtHelper.createToken(teacher.getId().longValue(),3));
                    }else {
                        return Result.fail().message("用户名或密码错误");
                    }
                    return Result.ok(map);
                } catch (Exception e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }
        }
        // 查无此用户,响应失败
        return Result.fail().message("查无此用户");
    }


    @GetMapping("/getVerifiCodeImage")
    public void getVerifiCodeImage(HttpServletRequest request, HttpServletResponse response){
        //得到验证码图片
        BufferedImage verifiCodeImage = CreateVerifiCodeImage.getVerifiCodeImage();
        //得到验证码
        String verifiCode = new String(CreateVerifiCodeImage.getVerifiCode() );
        //将验证码存入session
        HttpSession session = request.getSession();
        session.setAttribute("verifiCode" , verifiCode);
        //将图片响应到页面上
        try {
            ImageIO.write(verifiCodeImage,"JPEG",response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
